﻿<%@ Application Language="C#" %>


<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        OnTimerElapsed(null, null);
        System.Timers.Timer timer = new System.Timers.Timer(86400000);
        timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimerElapsed);
        timer.Interval = 86400000;
        timer.Enabled = true;
    }
    
    private static decimal getMonthAmount(int contractId)
    {
        Contract selectedContract = null;
        BankDataDataContext db = new BankDataDataContext();
        var contracts = from contract in db.Contracts where contract.ContractId == contractId select contract;
        if (contracts.Count() > 0)
        {
            selectedContract = contracts.First();
        }
        if (selectedContract != null)
        {
            decimal amount = (selectedContract.Amount - getPayedMainAmount(contractId)) / (selectedContract.TermLength - getMonthCountPayment(contractId));
            return amount;
        }
        return -1;
    }

    private static decimal getPayedMainAmount(int contractId)
    {
        BankDataDataContext db = new BankDataDataContext();
        var payments = from payment in db.ContractPayments where payment.ConractId == contractId select payment;
        decimal payedAmount = 0;
        foreach (ContractPayment contractPayment in payments)
        {
            payedAmount += contractPayment.MainAmount;
        }
        return payedAmount;
    }

    private static decimal getPayedPercentageAmount(int contractId)
    {
        BankDataDataContext db = new BankDataDataContext();
        var payments = from payment in db.ContractPayments where payment.ConractId == contractId select payment;
        decimal payedAmount = 0;
        foreach (ContractPayment contractPayment in payments)
        {
            payedAmount += contractPayment.PercentageAmount;
        }
        return payedAmount;
    }

    private static double getMonthCreditPercentage(int contractId)
    {
        BankDataDataContext db = new BankDataDataContext();
        Contract selectedContract = null;
        var contracts = from contract in db.Contracts where contract.ContractId == contractId select contract;
        if (contracts.Count() > 0)
        {
            selectedContract = contracts.First();
        }
        var creditCurrencies = from creditCurrency in db.CreditCurrencies
                               where creditCurrency.CreditId == selectedContract.CreditId &&
                                   creditCurrency.CurrencyId == selectedContract.CurrencyId
                               select creditCurrency;
        return creditCurrencies.First().Percentage / 12;
    }

    private static int getMonthCountFromLastPayment(int contractId)
    {
        BankDataDataContext db = new BankDataDataContext();
        var payments = from payment in db.ContractPayments where payment.ConractId == contractId select payment;
        Contract selectedContract = null;
        var contracts = from contract in db.Contracts where contract.ContractId == contractId select contract;
        if (contracts.Count() > 0)
        {
            selectedContract = contracts.First();
        }
        DateTime maxDate = selectedContract.CreationDate;
        foreach (ContractPayment contractPayment in payments)
        {
            if (contractPayment.Date > maxDate)
            {
                maxDate = contractPayment.Date;
            }
        }
        return System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(maxDate, DateTime.Now);
    }

    private static int getMonthCountPayment(int contractId)
    {
        BankDataDataContext db = new BankDataDataContext();
        var payments = from payment in db.ContractPayments where payment.ConractId == contractId select payment;
        Contract selectedContract = null;
        var contracts = from contract in db.Contracts where contract.ContractId == contractId select contract;
        if (contracts.Count() > 0)
        {
            selectedContract = contracts.First();
        }
        DateTime maxDate = selectedContract.CreationDate;
        foreach (ContractPayment contractPayment in payments)
        {
            if (contractPayment.Date > maxDate)
            {
                maxDate = contractPayment.Date;
            }
        }
        return System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(selectedContract.CreationDate, maxDate);
    }
    
    private static void OnTimerElapsed(object source, System.Timers.ElapsedEventArgs e)
    {
        BankDataDataContext db = new BankDataDataContext();
        var contracts = from contract in db.Contracts where contract.StatusId == 1 select contract;
        foreach (Contract contract in contracts)
        {
            DateTime contractCreationDate = contract.CreationDate;
            int monthDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(contractCreationDate, DateTime.Now);
            if (monthDiff <= 0)
            {
                continue;
            }
            int contractId = contract.ContractId;
            contractCreationDate = contractCreationDate.AddMonths(monthDiff);
            contractCreationDate = contractCreationDate.AddDays(-3);
            int days = System.Data.Linq.SqlClient.SqlMethods.DateDiffDay(contractCreationDate, DateTime.Now);
            if (days >= 3)
            {
                MailServer mailServer = new MailServer();
                monthDiff++;
                decimal paymentAmount = Math.Round((getMonthAmount(contractId) + (contract.Amount - getPayedMainAmount(contractId))
                * (decimal)(getMonthCreditPercentage(contractId) / 100)) * getMonthCountFromLastPayment(contractId), 2);
                if (paymentAmount > 0)
                {
                    mailServer.sendMailAboutNeedPayment(contract.Company.UserProfiles.First().CompanyEmail, contract.Credit.Name, paymentAmount.ToString(),
                        contract.Currency.Name, contract.TermLength.ToString());
                }
                if (days >= 14 || monthDiff > 0)
                {
                    mailServer.sendMailAboutNeedPaymentAfterTwoWeek(contract.Company.UserProfiles.First().CompanyEmail, contract.Credit.Name, paymentAmount.ToString(),
                        contract.Currency.Name, contract.TermLength.ToString());
                }
            }
        }
    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

    }
       
</script>
